#!/usr/python3.6.3/bin/python3
# -*- coding: utf-8 -*-


import requests
from time import sleep
import redis
from subprocess import Popen, call, PIPE


# 执行命令检测
def errorlist(stderrs, project, args):
    if stderrs:
        print('''\
        {}
        更新脚本出错了
        函数: {}
        参数: {}
        {}'''.format("*" * 50, project, args, stderrs))


# 拉取jar包
def check_svn():
    req = Popen(
        'svn co svn://127.0.0.1:3960/project/Release/ /usr/Release/',
        shell=True, stdout=PIPE, stderr=PIPE
    )
    # 不想输出svn拉取代码的详细信息，使用Popen
    (stdeout, stderrs) = req.communicate()
    # 打印svn版本号
    print(stdeout.decode('utf-8').split('\n')[-2])
    errorlist(stderrs, 'check_svn', "--" + 'svn')


# 替换jar包
def mover_file(mvfile):
    req = call(
        '\cp -rf /usr/Release/mahjong/{0} /www/mahjong_8888_20689/{0}'.format(
            mvfile), shell=True
    )
    errorlist(req, 'mover_file', str(mvfile))


# 杀掉服务
def kill_server(user, servername):
    print('*' * 10, "--------旧进程-------",  '*' * 10) 
    if not call("ps -ef | grep -v grep | grep {} | grep {} ".format(
            user, servername), shell=True):
        print('*' * 10, "--------新进程-------",  '*' * 10)
        req = call(
            "ps -ef | grep -v grep | grep {} | grep {} | awk '{{print $2}}'| "
            "xargs kill".format(user, servername), shell=True)
        errorlist(req, 'kill_server', str(user) + "--" + str(servername))
    else:
        print('*' * 50)
        print("用户名:{}, 进程:{}, 没有启动".format(user, servername))


# 启动服务
def start_server(user, path, servername):
    req = call("chown -R {0}.{0} {1}".format(
        user, path), shell=True)
    errorlist(req, 'start_server', str(user) + "--" + str(servername))
    req = Popen("cd {} && nohup sudo -u{} /usr/local/jdk1.7.0_80/bin/java -jar "
         "./{} --spring.config.location=./application.properties  "
         "> nohup.out 2>&1 &".format(path, user, servername), shell=True)
    call("ps -ef | grep -v grep | grep 'cd' | grep 'nohup' | grep 'game' | "
          "grep 'java -jar' | grep 'mahjong_8888_20689'| awk '{print $2}' "
          "| xargs kill", shell=True)


# 检测服务
# 检测端口
def test_port(port):
    req = Popen(
        "netstat -nltp | grep {} | awk '{{print $4}}' | cut -d: -f4".format(
            port), shell=True, stdout=PIPE, stderr=PIPE
    )
    (stdeout, stderrs) = req.communicate()
    if not str(port) in stdeout.decode('utf-8').replace('\n', ''):
        raise ValueError('端口检测 {} 不通过'.format(port))
    errorlist(stderrs, 'test_port', str(port))


# 检测进程
def test_process(user, servername, url=''):
    req = call(
        "ps -ef | grep -v grep | grep {} | grep {}".format(user, servername), shell=True
    )
    errorlist(req, 'test_process', str(user) + "--" + str(servername))
    if 'http' in url:
        test_url(url)


# web检测
def test_url(url):
    if requests.get(url).status_code == 200:
        print('*' * 10, "--------url {} 测试成功-------".format(url),  '*' * 10)
    else:
        print('*' * 10, "--------url {} 测试失败-------".format(url),  '*' * 10)
        errorlist("status_code != 200", "test_url", str(url))


# 查看日志
def tail_log(path):
    print('*' * 10, "--------日志打印-------",  '*' * 10)
    call("tail -n15 {}/logs/*.log".format(path), shell=True)


def flush_redis(*args, **kwargs):
    r = redis.Redis(host='127.0.0.1', password="L46xJMAzrWR3Myzs",  port=3961, db=1)
    r.flushdb()
    

def run(mvfile, mvproperties, user, servername, path, port, url=''):
    check_svn()
    mover_file(mvfile)
    mover_file(mvproperties)
    kill_server(user, servername)
    start_server(user, path, servername)
    sleep(25)
    test_process(user, servername, url)
    test_port(port)
    tail_log(path)


if __name__ == '__main__':
    message = {
        'api': ("game-api-provider/game-api-provider-1.0-SNAPSHOT.jar",
                "game-api-provider/application.properties",
                "www21",
                "game-api-provider-1.0-SNAPSHOT.jar",
                "/www/mahjong_8888_20689/game-api-provider/", 48877),
        'TGMJWEB': ("TGMJ/game-web-consumer/game-web-consumer-1.0-SNAPSHOT.jar",
                    "TGMJ/game-web-consumer/application.properties",
                    "www22",
                    "game-web-consumer-1.0-SNAPSHOT.jar",
                    "/www/mahjong_8888_20689/TGMJ/game-web-consumer/", 4150,
                    'http://***IP***:4150/speaker'),
        'TGMJSERVER': ("TGMJ/game-server-consumer/game-server-consumer-1.0-SNAPSHOT.jar",
                       "TGMJ/game-server-consumer/application.properties",
                       "www22",
                       "game-server-consumer-1.0-SNAPSHOT.jar",
                       "/www/mahjong_8888_20689/TGMJ/game-server-consumer/", 21915),
        'YCMJWEB': ("YCMJ/game-web-consumer/game-web-consumer-1.0-SNAPSHOT.jar",
                    "YCMJ/game-web-consumer/application.properties",
                    "www23",
                    "game-web-consumer-1.0-SNAPSHOT.jar",
                    "/www/mahjong_8888_20689/YCMJ/game-web-consumer/", 9057,
                    'http://***IP***:9057/speaker'),
        'YCMJSERVER': ("YCMJ/game-server-consumer/game-server-consumer-1.0-SNAPSHOT.jar",
                       "YCMJ/game-server-consumer/application.properties",
                       "www23",
                       "game-server-consumer-1.0-SNAPSHOT.jar",
                       "/www/mahjong_8888_20689/YCMJ/game-server-consumer/", 9969),
    }
    inp = input("""请输入指令:
    api
    TGMJWEB, TGMJSERVER
    YCMJWEB, YCMJSERVER
    APIS, SERVERS, WEBS
    flushRedis\n""")
    if inp == 'APIS':
        for i in message:
            run(*message[i])
    elif inp == 'flushRedis':
        flush_redis()
    elif inp == 'SERVERS':
        run(*message['TGMJSERVER'])
        run(*message['YCMJSERVER'])
    elif inp == 'WEBS':
        run(*message['TGMJWEB'])
        run(*message['YCMJWEB'])
    else:
        run(*message[inp])

